package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.CounterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.Collection;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 唯一计数器：同一个成员访问多次也只能算一次
 */
@Service("UniqueCounter")
@Slf4j
public class UniqueCounterServiceImpl implements CounterService {

    final String UNIQUE_COUNTER_KEY = "unique::counter";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 甚至都不需要初始化
     *
     * @param value
     * @return
     */
    @Override
    public boolean init(int value) {
//        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
//        opsForSet.add(UNIQUE_COUNTER_KEY, )
        throw new NotImplementedException();
    }

    @Override
    public long increase() {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        Long add = opsForSet.add(UNIQUE_COUNTER_KEY, iptl.get());
        log.info("添加成功标志：{}", add);
        iptl.remove();
        return opsForSet.size(UNIQUE_COUNTER_KEY);
    }

    @Override
    public long increase(int num) {
        throw new NotImplementedException();
    }

    @Override
    public long decrease() {
        throw new NotImplementedException();
    }

    @Override
    public long decrease(int num) {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        Long add = opsForSet.remove(UNIQUE_COUNTER_KEY, iptl.get());
        log.info("移除成功标志：{}", add);
        iptl.remove();
        return opsForSet.size(UNIQUE_COUNTER_KEY);
    }
}
